import 'dart:convert';
import 'dart:typed_data';

/// @author yichen
/// @date 2023/3/24下午2:24
class ByteBuf {
  ///字节数组
  List<int> _list = [];

  /// 当前缩影
  int _index = 0;

  /// 写入32位的int
  ByteBuf writeInt(int value) {
    return _writeInt(value, 4);
  }

  /// 写入64位的int
  ByteBuf writeLong(int value) {
    return _writeInt(value, 8);
  }

  /// 写入2位的int
  ByteBuf writeShort(int value) {
    return _writeInt(value, 2);
  }

  /// 写入1位的int
  ByteBuf writeBytes(List<int> list) {
    _list.addAll(list);
    return this;
  }

  /// 写入字符串
  ByteBuf writeString(String str) {
    _list.addAll(getUtf8Bytes(str));
    return this;
  }

  /// 写入字节数组
  ByteBuf writeByte(int value) {
    _list.add(value);
    return this;
  }

  /// 数字转成字节
  ByteBuf _writeInt(int value, int length) {
    for (int index = length; index > 0; index--) {
      final bits = 8 * (index - 1);
      if (bits > 0) {
        _list.add(value >> bits);
      } else {
        _list.add(value);
      }
    }
    return this;
  }

  /// 转换成字节数组
  Uint8List array() {
    return Uint8List.fromList(_list);
  }

  /// 获取utf8的字符串字节数组
  static List<int> getUtf8Bytes(String target) {
    return utf8.encode(target);
  }

  /// 创建
  static ByteBuf create(Uint8List uint8list) {
    final byteBuf = ByteBuf();
    // byteBuf._list = Int8List.fromList(uint8list);
    byteBuf._list = uint8list;
    return byteBuf;
  }

  /// 读取四个字节数字
  int readInt() {
    return _readInt(4);
  }

  /// 读取short类型
  int readShort() {
    return _readInt(2);
  }

  /// 读取short类型
  int readLong() {
    return _readInt(8);
  }

  /// 读取字节
  int readByte() {
    return _readInt(1);
  }

  /// 读取字节数组
  List<int> readBytes({int? length}) {
    int start = _index;
    if (length == null) {
      _index = _list.length - 1;
      return _list.sublist(start);
    }
    _index += length;
    return _list.sublist(start, _index);
  }

  /// 读取字符串
  String readString(int length) {
    final start = _index;
    _index += length;
    return utf8.decode(_list.sublist(start, _index));
  }

  /// 去读整数
  int _readInt(int length) {
    int num = 0;
    for (int i = length; i > 0; i--) {
      final bits = 8 * (i - 1);
      final value = _list[_index++];
      if (bits > 0) {
        num |= value << bits;
      } else {
        num |= value;
      }
    }
    return num;
  }
}
